package com.ai.chatapi.controller;

import com.ai.alibaba.bailian.service.AIChatService;
import com.ai.chatapi.serviceImpl.AiService;
import com.ai.deepSeek.service.DeepSeekService;
import com.ai.helper.HelpService;
import com.ai.kedaxunfei.SparkManager;
import com.ai.robot.RobotService;
import com.ai.util.VoiceRecognition;
import com.ai.util.langdu.TextToSpeech;
import com.ai.util.luying.Recorder;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.File;

/**
 * 整合语言处理和 AI 实现系统启动时加载资源，支持直接调用。
 * @author houwenpeng
 */
@Component
public class VoiceController {

    // 提前预备提示音文件路径
    private static final String PROMPT_AUDIO_PATH_SYSTEM1 =  "D:\\project\\AI\\src\\main\\resources\\system1.wav";
    private static final String PROMPT_AUDIO_PATH_SYSTEM2 =  "D:\\project\\AI\\src\\main\\resources\\system2.wav";
    private static final String PROMPT_AUDIO_PATH_SYSTEM3 =  "D:\\project\\AI\\src\\main\\resources\\ststem3.wav";
    private static final float PITCH_FACTOR = 1.0f;
    private final AiService aiService;
    private final VoiceRecognition voiceRecognition;
    private final SparkManager sparkManager;
    private final TextToSpeech speech;
    private final Recorder recorder;
    private final HelpService helpController;
    private final RobotService robotService;
    private final AIChatService aiChatService;
    private final DeepSeekService deepSeekService;


    // 构造函数注入依赖
    public VoiceController(AiService aiService, VoiceRecognition voiceRecognition,
                           SparkManager sparkManager, TextToSpeech speech,
                           Recorder recorder, HelpService helpController,RobotService robotService,AIChatService aiChatService,DeepSeekService deepSeekService) {
        this.aiService = aiService;
        this.voiceRecognition = voiceRecognition;
        this.sparkManager = sparkManager;
        this.speech = speech;
        this.recorder = recorder;
        this.helpController = helpController;
        this.robotService = robotService;
        this.aiChatService = aiChatService;
        this.deepSeekService = deepSeekService;

    }

    /**
     * 在项目启动时加载资源。
     */
    @PostConstruct
    public void initialize() {
        System.out.println("正在初始化资源...");

        // 启动监听线程
        new Thread(() -> {
            // 无限循环，等待唤醒并处理语音
            while (true) {
                String record = helpController.startListening(); // 监听唤醒词
                // 处理语音命令
                if (record != null) {
                    processVoiceCommand(record); // 处理语音命令
                }
            }
        }).start();

        System.out.println("资源加载完成，监听已启动。");
    }

    /**
     * 处理语音命令并生成 AI 回复。
     * @return AI 回复的文本
     */
    public String processVoiceCommand(String record) {
        try {
            // 将语音文件转换为文本
            String transcript = voiceRecognition.convertSpeechToText(new File(record));

            if (!ObjectUtils.isEmpty(transcript)){

                // 判断AI问题回答还是动作执行
                if (transcript.replaceAll("\\s+", "").contains("立刻执行")){

                    String b = ",当出现立刻执行的语句时,将这段话翻译为指令集,以key:value的形式输出成JSON 串，例如[\n" +
                            "    {\"上\": 10},\n" +
                            "    {\"右\": 8}\n" +
                            "  ],并且只要JSON串不要其他汉字回答";

                    //String iput ="“向前行走10米，然后向右行走8米”立刻执行" + b;

                    String iput = transcript + b;

                    String chat = aiChatService.chat(iput); // 调用AI模型获取回答 (需要链接网络)

                    //String chat = deepSeekService.deepSeek(iput); // 调用AI模型获取回答 (无需网络)

                    robotService.execute(chat);

                    helpController.playAudio(PROMPT_AUDIO_PATH_SYSTEM3,PITCH_FACTOR);

                    System.out.println("主人您的指令我已经执行完成，请问主人您还需要其他什么服务吗，期待下次为您服务~~~");
                    return null;
                }else {
                    helpController.playAudio(PROMPT_AUDIO_PATH_SYSTEM1,PITCH_FACTOR);

                    System.out.println("请您稍作等待,容赛博格同学仔细思考一下呢");

                    // sparkManager.sendHttpTOSpark(transcript); // 调用AI模型获取回答
                    // deepSeekService.deepSeek(iput); // 调用AI模型获取回答 (无需网络)

                    String aiResponse = "暂时未接入AI大模型,如需要接入联系管理员进行接入即可";

                    speech.speech(aiResponse);

                    return aiResponse;
                }
            }else {
                helpController.playAudio(PROMPT_AUDIO_PATH_SYSTEM2,PITCH_FACTOR);
                System.out.println("主人我没太明白您说的什么,能否对我重说一遍?");
            }

        } catch (Exception e) {
            helpController.playAudio(PROMPT_AUDIO_PATH_SYSTEM2,PITCH_FACTOR);
            System.out.println("主人我没太明白您说的什么，能否对我重说一遍?");
            System.err.println("处理语音命令时出错：" + e.getMessage());
            return "处理失败";

        }
        return null;
    }
}






































































































// 接口请求的形式
//package com.ai.chatapi.controller;
//
//import com.ai.chatapi.serviceImpl.AiService;
//import com.ai.helper.NewHelpController;
//import com.ai.kedaxunfei.SparkManager;
//import com.ai.util.VoiceRecognition;
//import com.ai.util.langdu.TextToSpeech;
//import com.ai.util.luying.Recorder;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.http.ResponseEntity;
//import org.springframework.http.HttpStatus;
//import java.io.File;
//
///**
// *
// * 整合语言处理 和 AI 来实现接口调用
// * @author houwenpeng
// */
//@RestController
//public class VoiceController {
//
//    @Autowired
//    private AiService aiService;
//    @Autowired
//    private VoiceRecognition voiceRecognition;
//
//    @Autowired
//    private SparkManager sparkManager;
//
//    @Autowired
//    private TextToSpeech speech;
//
//    @Autowired
//    private Recorder recorder;
//
//    @Autowired
//    private NewHelpController helpController;
//
//
//    /**
//     * 根据语言生成AI回答问题
//     * @return
//     */
//    @PostMapping("/ai")
//    public ResponseEntity<String> ai() {
//        try {
//
//            // 录音 监听器音频
//            String record = helpController.startListening();
//
//            // 录音 手动录音
//            //String record = recorder.record();
//
//            // 语音合成文本
//            String transcript = voiceRecognition.convertSpeechToText(new File(record));
//
//            // 使用科大讯飞模型生成AI回答/ 百度/ 阿里巴巴 等AI
//            String aiResponse = sparkManager.sendHttpTOSpark(transcript);
//
//            // 语音合成
//            speech.speech(aiResponse);
//
//            return ResponseEntity.status(HttpStatus.OK).body(aiResponse);
//
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing your request.");
//        }
//    }
//}






































































